package org.example;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.ExecutorSubscribableChannel;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;



//@Configuration
public class StompInterceptorConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
                
                // 心跳消息的识别标准：
                // 1. 无STOMP命令
                // 2. 消息体为空
                // 3. 包含heartbeat头
                if (accessor.getCommand() == null && 
                    message.getPayload() instanceof byte[] && 
                    ((byte[]) message.getPayload()).length == 0) {
                    System.out.println("[STOMP心跳] 类型: " + 
                        (channel instanceof ExecutorSubscribableChannel ? "接收" : "发送"));
                }
                return message;
            }
        });
    }
}